﻿#include "dialogdeviceselect.h"
#include "ui_dialogdeviceselect.h"
#include "QFontMetrics"


DialogDeviceSelect::DialogDeviceSelect(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DialogDeviceSelect)
{
    ui->setupUi(this);

    ui->verticalScrollBar->setDisabled(true);
    pDeviceArray = new QVector<Target*>;
}

DialogDeviceSelect::~DialogDeviceSelect()
{
    delete ui;
    delete pDeviceArray;
}


void DialogDeviceSelect::setSelections(QVector<Target*>* pDevices)
{
    pDeviceArray = pDevices;
    QList<DeviceWidget*> list = ui->frame->findChildren<DeviceWidget*>();

    for(auto & widget : std::as_const(list))
    {
        delete widget;
    }

    // 找到最长的设备名称
    quint16 tMaxWidth = 100;
    QFontMetrics fm(this->font());

    for(auto &device : std::as_const(*pDevices)) {
        QRect rect = fm.boundingRect(device->getDeviceName());
        if(tMaxWidth < rect.width()){
            tMaxWidth = rect.width();
        }
    }

    ui->frame->setFixedWidth(tMaxWidth * (1.0 + 50.0 / (float)tMaxWidth) + 50);
    this->setFixedWidth(ui->frame->width() + ui->verticalScrollBar->width());

    // 将配置文件中设备添加到连接设备下拉框选项中
    for(int i = 0; i < pDevices->count(); i++)
    {

        DeviceWidget* selectoption = new DeviceWidget(ui->frame);
        selectoption->setFixedWidth(ui->frame->width());
        selectoption->move(0, i * selectoption->height());
        QList<QLabel*> labellist = selectoption->findChildren<QLabel*>();
        for(auto &label: std::as_const(labellist))
        {
            label->setText((*pDevices)[i]->getDeviceName());
        }

        connect(ui->verticalScrollBar, &QScrollBar::valueChanged, this, [=](int value){
            selectoption->move(0, i * selectoption->height() - value);
        });
        if(pDevices->count() * selectoption->height() > ui->frame->height())
        {
            ui->verticalScrollBar->setEnabled(true);
            ui->verticalScrollBar->setMaximum(pDevices->count() * selectoption->height() - ui->frame->height());
        }
    }


    // 配置文件选择按钮功能
    connect(ui->buttonBox, &QDialogButtonBox::accepted, this, [=](){
        QVector<Target> devices;
        QList<DeviceWidget*> list = ui->frame->findChildren<DeviceWidget*>();
        for(auto &widget : std::as_const(list))
        {
            QList<QCheckBox*> checkbok = widget->findChildren<QCheckBox*>();
            if(checkbok[0]->isChecked())
            {
                QList<QLabel*> label = widget->findChildren<QLabel*>();
                for(auto &device : std::as_const(*pDeviceArray))
                {
                    if(0 == device->getDeviceName().compare(label[0]->text()))
                    {
                        devices.append(*device);
                        break;
                    }
                }
            }
        }
        emit selected(devices);
    });

    return;
}


